package top.hcode.hoj.schedule;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import top.hcode.hoj.common.LazyDao;
import top.hcode.hoj.manager.coll.ItechCollQuestionJudgeManger;
import top.hcode.hoj.service.LockService;

import java.util.List;

/**
 * 客观题评分
 *
 * @author orangej
 * @since 2025/2/17
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CollObjectiveQuestionJudgeJob {

    private final ItechCollQuestionJudgeManger judgeManger;
    private final LockService lockService;
    private final LazyDao dao;

    private static final String LOCK_KEY = "key:CollObjectiveQuestionJudgeJob";

    @Scheduled(cron = "0 0/30 * * * ?")
    public void execute() {
        boolean locked = false;
        try {
            locked = lockService.tryLock(LOCK_KEY, 120);
            if (!locked) {
                return;
            }

            List<String> collIdList = dao.queryString("select DISTINCT coll_id from coll_user_answer where judge_state = 0");
            for (String collId : collIdList) {
                log.info("judge objective question for coll : {}", collId);
                judgeManger.judgeAllObjective(collId);
            }
        } finally {
            if (locked) {
                lockService.releaseLock(LOCK_KEY);
            }
        }


    }
}
